<template>
  <div class="h-screen flex flex-col bg-gray-50 dark:bg-gray-900 transition-colors duration-300">
    <!-- 顶部工具栏 -->
    <div class="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm">
      <div class="flex items-center justify-between px-4 sm:px-6 py-3">
        <div class="flex items-center space-x-4">
          <h1 class="text-lg sm:text-xl font-semibold text-gray-900 dark:text-gray-100 flex items-center">
            <i class="fas fa-presentation text-purple-500 mr-2"></i>
            Markdown 演示文稿
      </h1>
          
          <!-- 主题选择器 -->
          <div class="flex items-center space-x-2">
          <select
              v-model="selectedTheme" 
              @change="applyTheme"
              class="text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500"
            >
              <option v-for="theme in availableThemes" :key="theme.value" :value="theme.value">
                {{ theme.label }}
              </option>
          </select>
          </div>
          
          <!-- 场景选择器 -->
          <div class="flex items-center space-x-2">
          <select
              v-model="selectedScenario" 
              @change="applyScenario"
              class="text-sm border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-1.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500"
            >
              <option v-for="scenario in scenarios" :key="scenario.value" :value="scenario.value">
                {{ scenario.label }}
              </option>
          </select>
          </div>
        </div>
        
        <div class="flex items-center space-x-2">
          <!-- 演示模式 -->
          <button
            @click="togglePresentMode"
            class="inline-flex items-center px-3 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg text-sm font-medium transition-colors duration-200"
          >
            <i class="fas fa-play mr-2"></i>
            <span class="hidden sm:inline">演示模式</span>
          </button>
          
          <!-- 导出按钮 -->
          <div class="relative">
          <button
              @click="toggleExportMenu"
              class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
          >
              <i class="fas fa-download mr-2"></i>
              导出
              <i class="fas fa-chevron-down ml-1 text-xs"></i>
          </button>
            
            <div v-if="showExportMenu" class="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-gray-700 rounded-lg shadow-lg border border-gray-200 dark:border-gray-600 z-50">
              <div class="py-1">
                <button
                  v-for="format in exportFormats"
                  :key="format.type"
                  @click="exportPresentation(format.type)"
                  class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center"
                >
                  <i :class="format.icon" class="mr-3 w-4 text-center"></i>
                  {{ format.label }}
                </button>
          </div>
</div>
</div>
</div>
</div>
</div>

    <!-- 主内容区域 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 编辑器和预览区域 -->
      <div class="flex-1 flex overflow-hidden">
        <!-- 编辑器面板 -->
        <div 
          class="bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col"
          :style="{ width: leftPanelWidth + 'px' }"
        >
          <!-- 编辑器头部 -->
          <div class="flex-shrink-0 flex items-center justify-between p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750">
            <div class="flex items-center space-x-3">
              <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                <i class="fas fa-code text-purple-500 mr-2"></i>
                Markdown 源码
              </h3>
              <span class="text-xs text-gray-500 dark:text-gray-400 bg-gray-200 dark:bg-gray-600 px-2 py-1 rounded">
                {{ slideCount }} 页幻灯片
              </span>
</div>
            
            <div class="flex items-center space-x-2">
              <button
                @click="insertTemplate"
                class="px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-600 rounded-lg hover:shadow-sm"
                title="插入模板"
              >
                <i class="fas fa-plus mr-1"></i>
                模板
              </button>
  </div>
</div>

          <!-- 代码编辑器 -->
          <div class="flex-1 relative">
            <textarea
              ref="editorTextarea"
              v-model="editorContent"
              @input="handleEditorInput"
              @keydown="handleKeydown"
              class="w-full h-full p-4 font-mono text-sm bg-transparent text-gray-900 dark:text-gray-100 resize-none border-0 focus:outline-none"
              :placeholder="placeholderText"
              spellcheck="false"
            ></textarea>
          </div>
        </div>

        <!-- 拖拽分隔条 -->
        <div
          @mousedown="startResize"
          class="w-1 bg-gray-200 dark:bg-gray-700 hover:bg-purple-500 cursor-col-resize transition-colors"
        ></div>

        <!-- 预览面板 -->
        <div class="flex-1 flex flex-col bg-white dark:bg-gray-800">
          <!-- 预览头部 -->
          <div class="flex-shrink-0 flex items-center justify-between p-3 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750">
            <h3 class="text-sm font-medium text-gray-900 dark:text-gray-100">
              <i class="fas fa-eye text-green-500 mr-2"></i>
              幻灯片预览
            </h3>
            
            <div class="flex items-center space-x-2">
              <button
                @click="prevSlide"
                :disabled="currentSlide <= 1"
                class="p-1.5 text-gray-600 dark:text-gray-400 hover:text-purple-600 dark:hover:text-purple-400 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="fas fa-chevron-left"></i>
              </button>
              <span class="text-xs text-gray-600 dark:text-gray-400 mx-2">
                {{ currentSlide }} / {{ slideCount }}
              </span>
              <button
                @click="nextSlide"
                :disabled="currentSlide >= slideCount"
                class="p-1.5 text-gray-600 dark:text-gray-400 hover:text-purple-600 dark:hover:text-purple-400 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="fas fa-chevron-right"></i>
                </button>
              </div>
          </div>
          
          <!-- 预览内容 -->
          <div class="flex-1 overflow-auto p-4 bg-gradient-to-br from-gray-50 to-white dark:from-gray-800 dark:to-gray-900">
            <!-- 空状态 -->
            <div 
              v-if="!editorContent.trim()" 
              class="h-full flex flex-col items-center justify-center text-gray-500 dark:text-gray-400"
            >
              <i class="fas fa-presentation text-6xl mb-4 opacity-20"></i>
              <p class="text-lg mb-2">创建您的演示文稿</p>
              <p class="text-sm mb-4">选择场景模板开始</p>
              <div class="grid grid-cols-2 gap-3 mb-6">
              <button
                  v-for="scenario in scenarios.slice(0, 4)"
                  :key="scenario.value"
                  @click="selectScenario(scenario.value)"
                  class="px-4 py-2 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 text-sm transition-all duration-200 hover:shadow-md"
                >
                  {{ scenario.label }}
              </button>
            </div>
              <!-- 使用提示 -->
              <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4 max-w-md">
                <h4 class="text-blue-800 dark:text-blue-200 font-medium mb-2">
                  <i class="fas fa-lightbulb mr-2"></i>
                  使用提示
                </h4>
                <ul class="text-xs text-blue-700 dark:text-blue-300 space-y-1">
                  <li>• 使用 <code>---</code> 分隔幻灯片</li>
                  <li>• 支持 Mermaid 流程图</li>
                  <li>• 使用 <kbd>←</kbd> <kbd>→</kbd> 键导航</li>
                  <li>• 支持多种主题风格</li>
                </ul>
          </div>
            </div>
            
            <!-- 幻灯片内容 -->
            <div
              v-else
              ref="slideContainer"
              class="slide-preview bg-white dark:bg-gray-800 rounded-xl shadow-2xl p-8 min-h-96 relative overflow-hidden transition-all duration-300"
              :class="[themeClasses, layoutClasses]"
            >
              <!-- 主题指示器 -->
              <div 
                class="absolute top-4 left-4 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-xs rounded-full font-medium z-10"
              >
                {{ availableThemes.find(t => t.value === selectedTheme)?.label }}
              </div>
              
              <!-- 幻灯片内容 -->
              <div 
                class="prose dark:prose-invert max-w-none transition-all duration-300 relative z-0"
                :class="slideContentClasses"
                v-html="renderedSlide"
              ></div>
          </div>
        </div>
      </div>
    </div>

      <!-- 底部缩略图导航 -->
      <div 
        v-if="editorContent.trim() && slideCount > 1"
        class="flex-shrink-0 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4"
      >
        <div class="flex items-center justify-between mb-3">
          <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100">
            <i class="fas fa-images text-purple-500 mr-2"></i>
            幻灯片导航
          </h4>
          <div class="flex items-center space-x-2">
            <button
              @click="scrollThumbnails('left')"
              class="p-1 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
            >
              <i class="fas fa-chevron-left"></i>
            </button>
            <button
              @click="scrollThumbnails('right')"
              class="p-1 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
            >
              <i class="fas fa-chevron-right"></i>
            </button>
      </div>
    </div>

        <div 
          ref="thumbnailContainer"
          class="flex space-x-3 overflow-x-auto scrollbar-hidden"
          style="scroll-behavior: smooth;"
    >
      <div 
            v-for="(slide, index) in allSlides"
            :key="`slide-${index}`"
            @click="goToSlide(index + 1)"
            class="flex-shrink-0 w-32 h-20 border-2 rounded-lg cursor-pointer transition-all duration-200 relative overflow-hidden"
            :class="[
              currentSlide === index + 1 
                ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/30' 
                : 'border-gray-300 dark:border-gray-600 hover:border-purple-300 bg-white dark:bg-gray-700'
            ]"
      >
        <div 
              class="w-full h-full p-2 text-xs overflow-hidden"
              :class="[
                'thumbnail-slide',
                themeClasses,
                currentSlide === index + 1 ? 'text-purple-700 dark:text-purple-300' : 'text-gray-600 dark:text-gray-400'
              ]"
              v-html="renderThumbnailSlide(slide.content)"
        ></div>
            <div class="absolute bottom-1 right-1 bg-black bg-opacity-60 text-white text-xs px-1 rounded">
              {{ index + 1 }}
      </div>
      </div>
    </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onUnmounted, watch } from 'vue'

// 响应式状态
const editorContent = ref('')
const selectedTheme = ref('apple-modern')
const selectedScenario = ref('business')
const currentSlide = ref(1)
const showExportMenu = ref(false)
const leftPanelWidth = ref(500)
const isRenderingMermaid = ref(false)
const mermaidRenderCount = ref(0)

// DOM 引用
const editorTextarea = ref<HTMLTextAreaElement>()
const slideContainer = ref<HTMLElement>()
const thumbnailContainer = ref<HTMLElement>()

// Mermaid 实例缓存
let mermaidInstance: any = null
let renderTimeout: NodeJS.Timeout | null = null

// 扩展主题配置
const availableThemes = [
  { value: 'apple-modern', label: '🍎 苹果现代风格' },
  { value: 'dark-cyberpunk', label: '🌌 赛博朋克' },
  { value: 'minimalist-white', label: '⚪ 极简白色' },
  { value: 'corporate-blue', label: '💼 企业蓝调' },
  { value: 'creative-gradient', label: '🎨 创意渐变' },
  { value: 'academic-serif', label: '📚 学术衬线' },
  { value: 'nature-green', label: '🌿 自然绿色' },
  { value: 'sunset-orange', label: '🌅 日落橙色' },
  { value: 'ocean-blue', label: '🌊 海洋蓝色' },
  { value: 'neon-purple', label: '💜 霓虹紫色' }
]

// 场景模板
const scenarios = [
  { value: 'business', label: '商务演示' },
  { value: 'technical', label: '技术分享' },
  { value: 'academic', label: '学术报告' },
  { value: 'creative', label: '创意展示' }
]

// 导出格式
const exportFormats = [
  { type: 'pdf', label: 'PDF 文档', icon: 'fas fa-file-pdf' },
  { type: 'pptx', label: 'PowerPoint', icon: 'fas fa-file-powerpoint' },
  { type: 'png', label: 'PNG 图片', icon: 'fas fa-image' },
  { type: 'html', label: 'HTML 网页', icon: 'fas fa-code' }
]

// 占位符文本
const placeholderText = `---
theme: apple-modern
title: 我的演示文稿
---

# 🎯 欢迎使用 Markdown 演示文稿

一个现代化的演示文稿工具

---

# ✨ 主要特性

- 🎨 丰富的主题风格
- 📊 支持 Mermaid 图表
- 🖼️ 缩略图导航
- ⚡ 实时预览

---

# 📊 流程图示例

\`\`\`mermaid
graph TD
    A[开始] --> B{判断条件}
    B -->|是| C[执行操作A]
    B -->|否| D[执行操作B]
    C --> E[结束]
    D --> E
\`\`\`

---

# 🔗 时序图示例

\`\`\`mermaid
sequenceDiagram
    participant A as 用户
    participant B as 系统
    participant C as 数据库
    
    A->>B: 发送请求
    B->>C: 查询数据
    C-->>B: 返回结果
    B-->>A: 响应数据
\`\`\`

---

# 🎉 谢谢观看

感谢您的关注！`

// 场景模板内容
const scenarioTemplates = {
  business: `---
theme: corporate-blue
title: 商务演示
---

# 📈 商务演示标题

副标题描述

---

# 🏢 关于我们

## 公司简介
- 📅 成立时间：2020年
- 🌐 业务范围：数字化转型
- 👥 团队规模：50+人

---

# 📊 业务流程图

\`\`\`mermaid
graph TD
    A[客户需求] --> B{需求分析}
    B -->|明确| C[方案设计]
    B -->|模糊| D[深入调研]
    D --> C
    C --> E[技术实施]
    E --> F[项目交付]
    F --> G[运营支持]
\`\`\`

---

# 📈 业绩图表

\`\`\`mermaid
xychart-beta
    title "销售业绩趋势"
    x-axis [Q1, Q2, Q3, Q4]
    y-axis "销售额(万元)" 0 --> 1000
    bar [200, 450, 650, 800]
    line [150, 400, 600, 750]
\`\`\`

---

# 🤝 谢谢观看

联系我们：contact@company.com`,

  technical: `---
theme: dark-cyberpunk
title: 技术分享
---

# ⚡ 技术分享
## 现代前端架构设计

---

# 🛠️ 技术栈概览

\`\`\`mermaid
graph TB
    subgraph "前端技术栈"
        A[Vue 3] --> B[TypeScript]
        A --> C[Composition API]
        B --> D[类型安全]
        C --> E[逻辑复用]
    end
    subgraph "构建工具"
        F[Vite] --> G[HMR]
        F --> H[ESBuild]
    end
    A --> F
\`\`\`

---

# 🔄 数据流图

\`\`\`mermaid
gitgraph
    commit id: "初始化项目"
    branch feature
    checkout feature
    commit id: "添加组件"
    commit id: "单元测试"
    checkout main
    merge feature
    commit id: "发布v1.0"
\`\`\`

---

# ❓ Q&A

有任何问题吗？`,

  academic: `---
theme: academic-serif
title: 学术报告
---

# 📖 研究标题
## 副标题

**研究者**: 姓名  
**机构**: 大学/研究院  
**日期**: 2024年

---

# 🔍 研究背景

## 问题陈述
- 研究问题1
- 研究问题2
- 研究问题3

---

# 📊 研究方法

\`\`\`mermaid
flowchart LR
    A[问题定义] --> B[文献调研]
    B --> C[实验设计]
    C --> D[数据收集]
    D --> E[数据分析]
    E --> F[结论验证]
\`\`\`

---

# 📝 结论与展望

## 结论
研究总结

## 未来工作
- 研究方向1
- 研究方向2`,

  creative: `---
theme: creative-gradient
title: 创意展示
---

# 🎨 创意展示
## 让想象力飞翔

---

# 🎯 设计原则

<div class="grid grid-cols-2 gap-8">
<div>
    <h2>简约至上</h2>
    <p>Less is More</p>
</div>
<div>
    <h2>用户中心</h2>
    <p>User First</p>
</div>
</div>

---

# 🌈 创意思维导图

\`\`\`mermaid
mindmap
  root((创意))
    灵感
      观察
      思考
      体验
    实现
      设计
      开发
      测试
    分享
      展示
      反馈
      迭代
\`\`\`

---

# 🎉 创意无限

**Keep Creating!**`
}

// 计算属性
const slideCount = computed(() => {
  if (!editorContent.value) return 0
  
  const slides = editorContent.value.split('---')
  const validSlides = slides.filter(slide => {
    const trimmed = slide.trim()
    return trimmed && !trimmed.startsWith('title:') && !trimmed.startsWith('theme:')
  })
  
  return Math.max(validSlides.length, 1)
})

const allSlides = computed(() => {
  if (!editorContent.value) return []
  
  const slides = editorContent.value.split('---')
  const validSlides = slides.filter(slide => {
    const trimmed = slide.trim()
    return trimmed && !trimmed.startsWith('title:') && !trimmed.startsWith('theme:')
  })
  
  return validSlides.map((content, index) => ({
    id: index + 1,
    content: content.trim()
  }))
})

const themeClasses = computed(() => {
  const baseClasses = 'transition-all duration-500'
  
  switch (selectedTheme.value) {
    case 'apple-modern':
      return `${baseClasses} font-sans text-gray-900 dark:text-gray-100 bg-gradient-to-br from-gray-50 to-white dark:from-gray-800 dark:to-gray-900 apple-modern-theme`
    case 'dark-cyberpunk':
      return `${baseClasses} font-mono bg-black text-cyan-400 cyberpunk-theme`
    case 'minimalist-white':
      return `${baseClasses} font-light text-gray-800 bg-white minimalist-theme`
    case 'corporate-blue':
      return `${baseClasses} font-sans text-blue-900 bg-gradient-to-br from-blue-50 to-indigo-100 corporate-theme`
    case 'creative-gradient':
      return `${baseClasses} font-sans text-white bg-gradient-to-br from-purple-600 via-pink-600 to-red-600 creative-theme`
    case 'academic-serif':
      return `${baseClasses} font-serif text-gray-900 bg-gray-50 academic-theme`
    case 'nature-green':
      return `${baseClasses} font-sans text-green-900 bg-gradient-to-br from-green-50 to-emerald-100 nature-theme`
    case 'sunset-orange':
      return `${baseClasses} font-sans text-orange-900 bg-gradient-to-br from-orange-100 to-red-200 sunset-theme`
    case 'ocean-blue':
      return `${baseClasses} font-sans text-blue-100 bg-gradient-to-br from-blue-900 to-cyan-800 ocean-theme`
    case 'neon-purple':
      return `${baseClasses} font-sans text-purple-100 bg-gray-900 neon-theme`
    default:
      return baseClasses
  }
})

const layoutClasses = computed(() => {
  return 'flex items-center justify-center text-center'
})

const slideContentClasses = computed(() => {
  const baseClasses = 'text-center max-w-4xl mx-auto'
  
  switch (selectedTheme.value) {
    case 'dark-cyberpunk':
      return `${baseClasses} cyberpunk-content`
    case 'creative-gradient':
      return `${baseClasses} creative-content`
    case 'academic-serif':
      return `${baseClasses} academic-content leading-relaxed`
    default:
      return baseClasses
  }
})

// 基于 markdown-it 的渲染引擎
const renderedSlide = computed(() => {
  if (!editorContent.value) return ''
  
  try {
    const slides = allSlides.value
    if (slides.length === 0) return ''
    
    const currentSlideIndex = Math.min(currentSlide.value - 1, slides.length - 1)
    const currentSlideContent = slides[currentSlideIndex]?.content || ''
    
    if (!currentSlideContent) return '<p class="text-gray-500 dark:text-gray-400">空白幻灯片</p>'
    
    // 预处理 Mermaid 图表
    let cleanContent = currentSlideContent
      .replace(/^layout:\s*\w+\s*$/gm, '') // 移除 layout 指令
      .replace(/^background:\s*.*$/gm, '') // 移除 background 指令
      .trim()
    
    cleanContent = cleanContent.replace(/```mermaid\n([\s\S]*?)\n```/g, (match, mermaidCode) => {
      const diagramId = `mermaid-slide-${currentSlide.value}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      return `<div class="mermaid-diagram-container my-8 relative" id="${diagramId}" data-mermaid="${encodeURIComponent(mermaidCode.trim())}">
        <div class="mermaid-loading absolute inset-0 flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-lg">
          <div class="flex items-center space-x-2 text-gray-600 dark:text-gray-400">
            <div class="animate-spin rounded-full h-4 w-4 border-2 border-blue-500 border-t-transparent"></div>
            <span class="text-sm">渲染图表中...</span>
          </div>
        </div>
      </div>`
    })
    
    const htmlContent = renderMarkdown(cleanContent)
    
    // 防抖渲染 Mermaid 图表
    if (renderTimeout) {
      clearTimeout(renderTimeout)
    }
    
    renderTimeout = setTimeout(() => {
      renderMermaidDiagrams()
    }, 300)
    
    return htmlContent
  } catch (error) {
    console.error('❌ 幻灯片渲染错误:', error)
    return '<div class="text-red-500 dark:text-red-400 p-4 rounded bg-red-100 dark:bg-red-900/30">渲染错误</div>'
  }
})

// 简化的 markdown 渲染器
function renderMarkdown(content: string): string {
  try {
    let html = content
      // 标题
      .replace(/^### (.*$)/gm, '<h3 class="text-xl font-semibold mb-4">$1</h3>')
      .replace(/^## (.*$)/gm, '<h2 class="text-2xl font-bold mb-6">$1</h2>')
      .replace(/^# (.*$)/gm, '<h1 class="text-4xl font-bold mb-8">$1</h1>')
      // 粗体和斜体
      .replace(/\*\*(.*?)\*\*/g, '<strong class="font-bold">$1</strong>')
      .replace(/\*(.*?)\*/g, '<em class="italic">$1</em>')
      // 链接
      .replace(/\[([^\]]+)\]\(([^\)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:text-blue-800 underline">$1</a>')
      // 列表
      .replace(/^- (.*$)/gm, '<li class="mb-2">$1</li>')
      .replace(/(<li>.*<\/li>)/s, '<ul class="list-disc list-inside mb-6 space-y-2">$1</ul>')
      // 段落
      .replace(/\n\n/g, '</p><p class="mb-4">')
      .replace(/^(?!<[hl]|<ul|<div)(.+)$/gm, '<p class="mb-4">$1</p>')
      // 代码块
      .replace(/```(\w+)?\n([\s\S]*?)\n```/g, '<pre class="bg-gray-100 dark:bg-gray-800 rounded-lg p-4 overflow-x-auto mb-6"><code class="text-sm">$2</code></pre>')
    
    return html
          } catch (error) {
    console.error('❌ Markdown 渲染失败:', error)
    return '<div class="text-red-500 p-4 rounded bg-red-100">Markdown 渲染失败</div>'
  }
}

// 缩略图渲染
function renderThumbnailSlide(content: string): string {
  try {
    // 简化版渲染，只显示标题和主要内容
    let simplified = content
      .replace(/```mermaid\n([\s\S]*?)\n```/g, '<div class="text-xs text-center">📊 图表</div>')
      .replace(/^# (.*$)/gm, '<div class="font-bold text-xs mb-1">$1</div>')
      .replace(/^## (.*$)/gm, '<div class="font-medium text-xs">$1</div>')
      .replace(/^### (.*$)/gm, '<div class="text-xs">$1</div>')
      .replace(/^- (.*$)/gm, '• $1')
      .replace(/\*\*(.*?)\*\*/g, '$1')
      .replace(/\*(.*?)\*/g, '$1')
      .slice(0, 100) // 限制长度
    
    return simplified || '<div class="text-xs text-gray-400">空白页</div>'
  } catch {
    return '<div class="text-xs text-red-400">错误</div>'
  }
}

// 初始化 Mermaid
async function initMermaid() {
  try {
    if (mermaidInstance) return mermaidInstance
    
    console.log('🎯 正在初始化 Mermaid...')
    
    const { default: mermaid } = await import('mermaid')
    
    // 配置 Mermaid
    mermaid.initialize({
      startOnLoad: false,
      theme: selectedTheme.value.includes('dark') || selectedTheme.value === 'dark-cyberpunk' ? 'dark' : 'default',
      securityLevel: 'loose',
      fontFamily: getComputedStyle(document.body).fontFamily,
      logLevel: 'error',
      flowchart: {
        useMaxWidth: true,
        htmlLabels: true
      },
      sequence: {
        diagramMarginX: 50,
        diagramMarginY: 10,
        useMaxWidth: true,
        mirrorActors: true
      }
    })
    
    mermaidInstance = mermaid
    console.log('✅ Mermaid 初始化成功')
    
    return mermaidInstance
  } catch (error) {
    console.error('❌ Mermaid 初始化失败:', error)
    throw error
  }
}

// 渲染 Mermaid 图表 (优化版)
async function renderMermaidDiagrams() {
  if (isRenderingMermaid.value) {
    console.log('⏳ Mermaid 正在渲染中，跳过重复渲染')
    return
  }
  
  const mermaidContainers = document.querySelectorAll('.mermaid-diagram-container')
  if (mermaidContainers.length === 0) return
  
  isRenderingMermaid.value = true
  mermaidRenderCount.value++
  const currentRenderCount = mermaidRenderCount.value
  
  try {
    console.log(`🎯 开始渲染 ${mermaidContainers.length} 个 Mermaid 图表`)
    
    const mermaid = await initMermaid()
    
    // 更新主题配置
    mermaid.initialize({
      startOnLoad: false,
      theme: selectedTheme.value.includes('dark') || selectedTheme.value === 'dark-cyberpunk' ? 'dark' : 'default',
      securityLevel: 'loose',
      fontFamily: getComputedStyle(document.body).fontFamily,
      logLevel: 'error'
    })
    
    // 并行渲染所有图表
    const renderPromises = Array.from(mermaidContainers).map(async (container, index) => {
      // 检查是否有新的渲染请求
      if (currentRenderCount !== mermaidRenderCount.value) {
        console.log('🔄 检测到新的渲染请求，取消当前渲染')
        return
      }
      
      const mermaidCode = decodeURIComponent(container.getAttribute('data-mermaid') || '')
      if (!mermaidCode) return
      
      try {
        const uniqueId = `mermaid-${Date.now()}-${index}-${Math.random().toString(36).substr(2, 9)}`
        
        console.log(`📊 渲染图表 ${index + 1}/${mermaidContainers.length}:`, mermaidCode.substring(0, 50) + '...')
        
        // 使用 render 方法而不是 renderAsync
        const { svg } = await mermaid.render(uniqueId, mermaidCode)
        
        // 再次检查渲染是否被取消
        if (currentRenderCount !== mermaidRenderCount.value) {
          console.log('🔄 渲染被新请求取消')
          return
        }
        
        // 检查容器是否还存在
        if (!container.parentNode || !document.body.contains(container)) {
          console.log('⚠️ 容器已被移除，跳过渲染')
          return
        }
        
        // 移除加载状态
        const loadingElement = container.querySelector('.mermaid-loading')
        if (loadingElement) {
          loadingElement.remove()
        }
        
        // 插入 SVG
        if (svg) {
          container.innerHTML = svg
          
          const svgElement = container.querySelector('svg')
          if (svgElement) {
            // 应用样式
            svgElement.style.maxWidth = '100%'
            svgElement.style.height = 'auto'
            svgElement.style.display = 'block'
            svgElement.style.margin = '0 auto'
            svgElement.classList.add('shadow-lg', 'rounded-lg')
            
            // 主题特定样式
            if (selectedTheme.value === 'dark-cyberpunk') {
              svgElement.style.filter = 'drop-shadow(0 0 10px rgba(0, 255, 255, 0.3))'
            }
          }
          
          console.log(`✅ 图表 ${index + 1} 渲染成功`)
        }
      } catch (error) {
        console.error(`❌ 图表 ${index + 1} 渲染失败:`, error)
        
        if (container.parentNode && document.body.contains(container)) {
          container.innerHTML = `
            <div class="text-red-500 dark:text-red-400 p-4 text-center border border-red-200 dark:border-red-800 rounded-lg bg-red-50 dark:bg-red-900/20">
              <i class="fas fa-exclamation-triangle text-xl mb-2"></i>
              <p class="font-medium">图表渲染失败</p>
              <p class="text-xs opacity-75 mt-1">请检查 Mermaid 语法</p>
              <button onclick="window.location.reload()" class="mt-2 px-3 py-1 bg-red-500 text-white rounded text-xs hover:bg-red-600">
                重新加载
              </button>
            </div>
          `
        }
      }
    })
    
    await Promise.allSettled(renderPromises)
    console.log('✅ 所有 Mermaid 图表渲染完成')
    
  } catch (error) {
    console.error('❌ Mermaid 批量渲染失败:', error)
  } finally {
    isRenderingMermaid.value = false
  }
}

// 手动重新渲染
function forceRenderMermaid() {
  mermaidRenderCount.value++
  renderMermaidDiagrams()
}

// 监听主题变化，重新渲染图表
watch(selectedTheme, () => {
  nextTick(() => {
    forceRenderMermaid()
  })
})

// 监听当前页变化，重新渲染图表
watch(currentSlide, () => {
  nextTick(() => {
    forceRenderMermaid()
  })
})

// 方法
function applyTheme() {
  console.log('应用主题:', selectedTheme.value)
}

function applyScenario() {
  console.log('应用场景:', selectedScenario.value)
}

function selectScenario(scenario: string) {
  selectedScenario.value = scenario
  editorContent.value = scenarioTemplates[scenario as keyof typeof scenarioTemplates] || placeholderText
}

function togglePresentMode() {
  console.log('进入演示模式')
}

function toggleExportMenu() {
  showExportMenu.value = !showExportMenu.value
}

function exportPresentation(format: string) {
  showExportMenu.value = false
  console.log(`导出为 ${format}`)
}

function insertTemplate() {
  console.log('插入模板')
}

function handleEditorInput() {
  // 编辑器输入处理
}

function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Tab') {
    event.preventDefault()
    const textarea = event.target as HTMLTextAreaElement
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    
    editorContent.value = editorContent.value.substring(0, start) + '  ' + editorContent.value.substring(end)
    
    setTimeout(() => {
      textarea.selectionStart = textarea.selectionEnd = start + 2
    })
  }
}

function prevSlide() {
  if (currentSlide.value > 1) {
    currentSlide.value--
  }
}

function nextSlide() {
  if (currentSlide.value < slideCount.value) {
    currentSlide.value++
  }
}

function goToSlide(slideNumber: number) {
  if (slideNumber >= 1 && slideNumber <= slideCount.value) {
    currentSlide.value = slideNumber
  }
}

function scrollThumbnails(direction: 'left' | 'right') {
  if (!thumbnailContainer.value) return
  
  const scrollAmount = 200
  const currentScroll = thumbnailContainer.value.scrollLeft
  
  if (direction === 'left') {
    thumbnailContainer.value.scrollTo({
      left: currentScroll - scrollAmount,
      behavior: 'smooth'
    })
  } else {
    thumbnailContainer.value.scrollTo({
      left: currentScroll + scrollAmount,
      behavior: 'smooth'
    })
  }
}

// 面板拖拽
let isResizing = false

function startResize(event: MouseEvent) {
  isResizing = true
  document.addEventListener('mousemove', doResize)
  document.addEventListener('mouseup', endResize)
  event.preventDefault()
}

function doResize(event: MouseEvent) {
  if (!isResizing) return
  
  const container = document.querySelector('.h-screen')
  if (!container) return
  
  const containerRect = container.getBoundingClientRect()
  const newWidth = event.clientX - containerRect.left
  
  leftPanelWidth.value = Math.max(300, Math.min(window.innerWidth * 0.7, newWidth))
}

function endResize() {
  isResizing = false
  document.removeEventListener('mousemove', doResize)
  document.removeEventListener('mouseup', endResize)
}

// 键盘导航
function handleKeyNavigation(event: KeyboardEvent) {
  if (event.target === document.body || (event.target as HTMLElement).tagName !== 'TEXTAREA') {
    switch (event.key) {
      case 'ArrowLeft':
        event.preventDefault()
        prevSlide()
        break
      case 'ArrowRight':
        event.preventDefault()
        nextSlide()
        break
      case 'F5':
        event.preventDefault()
        forceRenderMermaid()
        break
    }
  }
}

onMounted(() => {
  editorContent.value = placeholderText
  document.addEventListener('keydown', handleKeyNavigation)
  
  // 预加载 Mermaid
  initMermaid().catch(error => {
    console.error('预加载 Mermaid 失败:', error)
  })
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyNavigation)
  
  // 清理定时器
  if (renderTimeout) {
    clearTimeout(renderTimeout)
  }
})
</script>

<style scoped>
.slide-preview {
  min-height: 500px;
  aspect-ratio: 16/9;
}

.prose {
  max-width: none;
}

.scrollbar-hidden {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.scrollbar-hidden::-webkit-scrollbar {
  display: none;
}

/* 主题特定样式 */
.apple-modern-theme {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  border-radius: 16px;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.15);
}

.cyberpunk-theme {
  background: linear-gradient(135deg, #000000 0%, #1a1a2e 50%, #16213e 100%);
  border: 2px solid #00ffff;
  box-shadow: 0 0 30px rgba(0, 255, 255, 0.3), inset 0 0 30px rgba(0, 255, 255, 0.1);
}

.cyberpunk-theme .cyberpunk-content {
  text-shadow: 0 0 10px currentColor;
}

.minimalist-theme {
  border: 1px solid #e5e7eb;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.corporate-theme {
  border: 1px solid #3b82f6;
  box-shadow: 0 20px 25px -5px rgba(59, 130, 246, 0.1);
}

.creative-theme {
  border-radius: 20px;
  box-shadow: 0 25px 50px -12px rgba(147, 51, 234, 0.25);
}

.creative-theme .creative-content {
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.academic-theme {
  border: 2px solid #6b7280;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}

.academic-theme .academic-content {
  line-height: 1.8;
}

.nature-theme {
  border: 2px solid #10b981;
  box-shadow: 0 20px 25px -5px rgba(16, 185, 129, 0.1);
}

.sunset-theme {
  border: 2px solid #f97316;
  box-shadow: 0 20px 25px -5px rgba(249, 115, 22, 0.15);
}

.ocean-theme {
  border: 2px solid #0891b2;
  box-shadow: 0 25px 50px -12px rgba(8, 145, 178, 0.25);
}

.neon-theme {
  background: radial-gradient(circle at center, #1a1a2e 0%, #000000 100%);
  border: 2px solid #8b5cf6;
  box-shadow: 0 0 30px rgba(139, 92, 246, 0.4), inset 0 0 30px rgba(139, 92, 246, 0.1);
}

.thumbnail-slide {
  transform: scale(0.8);
  transform-origin: top left;
}
</style> 